import { Injectable, inject } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse,
  HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { MessageService } from '../services/message.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private authService = inject(AuthService);
  private router = inject(Router);
  private messageService = inject(MessageService);

  private readonly BASE_URL = 'http://localhost:8000/api/v1';

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // 处理请求
    const modifiedRequest = this.addAuthHeader(this.addBaseUrl(request));

    return next.handle(modifiedRequest).pipe(
      tap((event: HttpEvent<unknown>) => {
        // // 处理成功响应
        // if (event instanceof HttpResponse) {
        //   console.log('请求成功:', event.url, '状态码:', event.status);
        // }
      }),
      catchError((error: HttpErrorResponse) => {
        return this.handleError(error);
      })
    );
  }

  /**
   * 添加基地址
   */
  private addBaseUrl(request: HttpRequest<unknown>): HttpRequest<unknown> {
    // 如果URL已经是完整的HTTP URL，则不添加基地址
    if (request.url.startsWith('http://') || request.url.startsWith('https://')) {
      return request;
    }

    // 添加基地址
    const apiUrl = `${this.BASE_URL}${request.url.startsWith('/') ? '' : '/'}${request.url}`;

    return request.clone({
      url: apiUrl
    });
  }

  /**
   * 添加认证头
   */
  private addAuthHeader(request: HttpRequest<unknown>): HttpRequest<unknown> {
    const token = this.authService.getToken();

    // 如果有token且不是登录/注册等不需要token的请求
    if (token && this.shouldAddAuthHeader(request.url)) {
      return request.clone({
        setHeaders: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
    }

    // 对于不需要token的请求，仍然设置Content-Type
    return request.clone({
      setHeaders: {
        'Content-Type': 'application/json'
      }
    });
  }

  /**
   * 判断是否应该添加认证头
   */
  private shouldAddAuthHeader(url: string): boolean {
    // 不需要token的端点
    const excludeUrls = [
      '/auth/signin',
      '/auth/signup',
      '/auth/forgot-password-code',
      '/auth/recover-password',
      '/auth/verify-user',
      '/auth/send-verification-email'
    ];

    return !excludeUrls.some(excludeUrl => url.includes(excludeUrl));
  }

  /**
   * 处理HTTP错误
   */
  private handleError(error: HttpErrorResponse): Observable<never> {
    let errorMessage = '发生未知错误';

    switch (error.status) {
      case 400:
        errorMessage = error.error?.message || '请求参数错误';
        break;
      case 401:
        errorMessage = '未授权，请重新登录';
        this.handleUnauthorized();
        break;
      case 403:
        errorMessage = '没有权限访问此资源';
        break;
      case 404:
        errorMessage = '请求的资源不存在';
        break;
      case 422:
        errorMessage = this.handleValidationErrors(error.error);
        break;
      case 500:
        errorMessage = '服务器内部错误';
        break;
      case 502:
        errorMessage = '网关错误';
        break;
      case 503:
        errorMessage = '服务暂时不可用';
        break;
      case 0:
        errorMessage = '网络连接失败，请检查网络设置';
        break;
      default:
        errorMessage = error.error?.message || `HTTP错误: ${error.status}`;
    }

    console.error('HTTP请求错误:', {
      status: error.status,
      message: errorMessage,
      url: error.url,
      error: error.error
    });

    // 显示错误消息（除了401错误，因为401会自动跳转到登录页）
    if (error.status !== 401) {
      this.messageService.error(errorMessage);
    }

    // 返回用户友好的错误信息
    const userError = new HttpErrorResponse({
      error: {
        ...error.error,
        userMessage: errorMessage
      },
      headers: error.headers,
      status: error.status,
      statusText: error.statusText,
      url: error.url || undefined
    });

    return throwError(() => userError);
  }

  /**
   * 处理401未授权错误
   */
  private handleUnauthorized(): void {
    // 清除本地存储的认证信息
    this.authService.logout();

    // 跳转到登录页
    this.router.navigate(['/login']);
  }

  /**
   * 处理表单验证错误
   */
  private handleValidationErrors(errorResponse: any): string {
    if (errorResponse?.errors) {
      // 处理Laravel风格的验证错误
      const errors = errorResponse.errors;
      const errorMessages: string[] = [];

      for (const field in errors) {
        if (errors[field] && Array.isArray(errors[field])) {
          errorMessages.push(...errors[field]);
        }
      }

      return errorMessages.join('；');
    }

    return errorResponse?.message || '数据验证失败';
  }
}
